/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.autoconfigure.swagger2;

import cn.hutool.core.collection.CollectionUtil;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.HttpAuthenticationScheme;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * Swagger2 3.x版本配置<br>
 * <a href='https://swagger.io/'>swagger2 官网</a> <br>
 * <a href='https://doc.xiaominfo.com/'>knife4j 官网</a> <br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@EnableOpenApi
@Configuration
@EnableConfigurationProperties(Swagger2Properties.class)
@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true")
@ConfigurationProperties(prefix = "springfox.swagger2")
public class Swagger2Configuration {

  /**
   * 创建API应用 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现， 本例采用指定扫描的包路径来定义指定要建立API的目录。
   */
  @Bean
  public Docket createRestfulApi(
      @Qualifier("star.Swagger2Properties") Swagger2Properties properties) {
    String tokenName = properties.getTokenName();
    return new Docket(DocumentationType.OAS_30)
        .apiInfo(apiInfo(properties))
        .select()
        .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
        .paths(PathSelectors.any())
        .build()
        .securityContexts(CollectionUtil.newArrayList(securityContexts(tokenName)))
        .securitySchemes(securitySchemes(tokenName));
  }

  private List<SecurityScheme> securitySchemes(String tokenName) {
    List<SecurityScheme> arrayList = new ArrayList<>();
    arrayList.add(new ApiKey(tokenName, tokenName, "header"));
    arrayList.add(basicAuthScheme());
    return arrayList;
  }

  private SecurityContext securityContexts(String tokenName) {
    return SecurityContext.builder()
        .securityReferences(defaultAuth(tokenName))
        // @Deprecated -> .forPaths(PathSelectors.any())
        .operationSelector(operationContext -> true)
        .build();
  }

  private List<SecurityReference> defaultAuth(String tokenName) {
    AuthorizationScope authorizationScope = new AuthorizationScope("global", "所有请求");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    List<SecurityReference> arrayList = new ArrayList<>();
    arrayList.add(new SecurityReference(tokenName, authorizationScopes));
    arrayList.add(basicAuthReference());

    return arrayList;
  }

  private SecurityScheme basicAuthScheme() {
    return HttpAuthenticationScheme.BASIC_AUTH_BUILDER.name("Authorization").build();
  }

  private SecurityReference basicAuthReference() {
    return new SecurityReference("Authorization", new AuthorizationScope[0]);
  }

  /** 创建该API的基本信息 访问地址：http://host:ip/swagger-ui.html */
  private ApiInfo apiInfo(Swagger2Properties swagger2) {
    Contact contact =
        new Contact(swagger2.getAuthor(), swagger2.getWebSiteUrl(), swagger2.getEmail());

    return new ApiInfoBuilder()
        .title(swagger2.getTitle())
        .description(swagger2.getDescription())
        .termsOfServiceUrl(swagger2.getTermsOfServiceUrl())
        .contact(contact)
        .version(swagger2.getVersion())
        .build();
  }
}
